package com.hue.concurrent.day07;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * CAS和AtomicInteger的使用
 */
public class Demo01 {
    public static void main(String[] args) throws InterruptedException {
        Account account = new Account(10000);
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            Thread thread = new Thread(() -> {
//                account.reduce(10);
                account.reduce1(10);
            });
            threadList.add(thread);
        }
        for (Thread thread : threadList) {
            thread.start();
        }

        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(account.getBalance());
    }

    public static class Account {
        private AtomicInteger atomicInteger;

        public Account(int banlance) {
            this.atomicInteger = new AtomicInteger(banlance);
        }

        /**
         * 获取余额
         *
         * @return
         */
        public int getBalance() {
            return atomicInteger.get();
        }

        /**
         * 消费余额
         */
        public void reduce(int money) {
            int balance = 0;
            int modifyBalance = 0;
            do {
                //获取余额
                balance = atomicInteger.get();
                //修改之后的余额
                modifyBalance = balance - money;
            } while (!atomicInteger.compareAndSet(balance, modifyBalance));
        }

        /**
         * 使用api操作原子整型
         */
        public void reduce1(int money) {
            atomicInteger.addAndGet(-money);
        }
    }
}
